package hu.bme.gabor.onlab;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class Communication {
	
	private String url;
	private String tomb[];

	
	public Communication() {
		this.url = MainActivity.getServerName();
	}
	
    public String getDataFromAvr(int type, int param){
        HttpClient httpclient = new DefaultHttpClient();
        
        HttpGet httpget = null;
        
        if(type==0)
        	httpget = new HttpGet(url+"?mobil=dev");
        if(type==1)
        	httpget = new HttpGet(url+"?mobil=temp");
        
        try {
			HttpResponse response = httpclient.execute(httpget);
			StatusLine sl = response.getStatusLine();
			Log.d("myapp", "status code: "+sl.getStatusCode());
			HttpEntity entity = response.getEntity();
			InputStream instream = entity.getContent();
			BufferedReader reader = new BufferedReader( new InputStreamReader(instream));
			
			StringBuilder sb = new StringBuilder();
			String line = null;
			try {
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
				
				String data = sb.toString();
				String delimiter = ",";
				
				tomb = data.split(delimiter);
		        
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (instream != null){
					try {
						instream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
				
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        return tomb[param];
    	
    }
    
    
    public void sendDataToAvr(boolean checked, int button){
    	
    	HttpClient httpclient = new DefaultHttpClient();
    	
    	HttpPost httppost;
    	if(checked){
    		httppost = new HttpPost(url+"?dev"+button+"=1");	// ezzel be lehet kapcsolni
    	}else{
    		httppost = new HttpPost(url+"?dev"+button+"=0");	// ezzel meg ki
    	}
    	try {
    		httpclient.execute(httppost);
    	} catch (Exception e) {
    		e.printStackTrace();
    		
    	}
    }
}
